from rest_framework import serializers

from modulars.models import Modulars
from testcases.models import Testcases
from utils import validates


class ModularsAnotherSerializer(serializers.ModelSerializer):

    project = serializers.StringRelatedField(help_text='项目名称')
    # 项目ID
    pid = serializers.IntegerField(write_only=True, validators=[validates.whether_existed_project_id])
    # 模块ID
    mid = serializers.IntegerField(write_only=True, validators=[validates.whether_existed_modulars_id])
    class Meta:
        model = Modulars
        fields = ('id', 'name', 'project', 'pid', 'mid')
        extra_kwargs = {
            'name': {
                'read_only': True
            },
            'project': {
                'read_only': True
            }
        }

    def validate(self, attrs):
        """
        校验项目ID是否与模块ID一致
        :param attrs:
        :return:
        """
        if not Modulars.objects.filter(id=attrs['mid'], project_id=attrs['pid'], is_delete=False).exists():
            raise serializers.ValidationError('项目和模块信息不对应')
        return attrs



class TestcasesSerializer(serializers.ModelSerializer):
    print(validates)
    """
    用例序列化器
    """
    modular = ModularsAnotherSerializer(help_text='所属接口和项目信息')

    class Meta:
        model = Testcases
        fields = ('id', 'name', 'modular', 'include', 'author', 'request')
        extra_kwargs = {
            'include': {
                'write_only': True
            },
            'request': {
                'write_only': True
            }
        }

    def create(self, validated_data):
        interface_dict = validated_data.pop('modular')
        validated_data['modular_id'] = interface_dict['mid']
        return Testcases.objects.create(**validated_data)

    def update(self, instance, validated_data):
        if 'modular' in validated_data:
            interface_dict = validated_data.pop('modular')
            validated_data['modular_id'] = interface_dict['mid']
        return super().update(instance, validated_data)




class TestcasesRunSerializer(serializers.ModelSerializer):
    """
    运行测试用例序列化器
    """
    env_id = serializers.IntegerField(write_only=True,
                                      help_text='环境变量ID',
                                      validators=[validates.whether_existed_env_id])

    class Meta:
        model = Testcases
        fields = ('id', 'env_id')


